import React, { useEffect, useState } from 'react'
import ProForm from '@ant-design/pro-form'
import { Checkbox, Form, Input, message, Modal, Skeleton, TreeSelect } from 'antd'
import { addPerson, getRoles, getUserDetail, updateUser } from '@/services/people'
import { getSections } from '@/services/section'
import FileUpload from '@/components/Upload'

const CreateOrEdit = (props) => {
  const { isModalVisible, modalIsShow, userinfo, actionRef, editId } = props
  // 设置角色
  const [allRoles, setRoles] = useState([])
  // 表单的初始值(用户的)
  const [userInfoInitValues, setUserInfoInitValues] = useState(undefined)
  // 树形组件
  const [treeData, setTreeData] = useState([])
  // 获取用户头像地址
  const [UserUrl, setUserUrl] = useState(undefined)
  const [form] = Form.useForm()
  // 行为的类型
  const type = editId === undefined ? '添加' : '编辑'
  //定义Form实例 用来操作表单
  const [formObj] = ProForm.useForm()
  /**
   * 通过id获取用户的数据
   */
  useEffect(async () => {
    // 获取部门的列表
    let sectionList = await getSections()
    setTreeData(sectionList.data)
    const treeData = sectionList.data.map(item => {
      return {
        key: item.id,
        value: item.id,
        title: item.name,
        children: item.children.map(item => {
          return {
            key: item.id,
            value: item.id,
            title: item.name,
          }
        })
      }
    })
    setTreeData(treeData)
    // 获取角色列表
    let rolelist = await getRoles()
    setRoles(rolelist.data)
    // 发送请求获取用户的详情
    if (editId !== undefined) {
      let response = await getUserDetail(editId)
      setUserInfoInitValues({
        id: editId,
        name: response.name,
        username: response.username,
        id_card: response.id_card,
        email: response.email,
        phone: response.phone,
        avatar: response.avatar,
        avatar_url: response.avatar_url,
        status: response.status,
        section: response.section.data.map((item) => {
          return item.id
        }),
        roles: response.roles.data.map((item) => {
          return item.id
        })
      })
      setUserUrl(response.avatar_url)
    }
  }, [])

  /**
   * 提交表单  用户的编辑或者添加
   * @returns {Promise<{pagination: *, data: *, message: string}>}
   * @param value
   */
  const handleSubmit = async (value) => {
    // 判断editId
    if (editId === undefined) {
      //添加的方法
      let response = await addPerson(value)
      if (response === '') {
        message.success(`${type}成功`)
        //  刷新表格数据
        actionRef.current.reload()
        // 关闭模态框
        modalIsShow(false)
      }
    } else {
      let response = await updateUser(value)
      // 这里进行结果的判断
      if (response === '') {
        message.success(`${type}成功`)
        actionRef.current.reload()
        modalIsShow(false)
      }
    }
  }

  /**
   * 用户头像地址
   */
  const EditUserUrl = url => {
    setUserUrl(url)
  }

  /**
   * 文件上传成功后设置文件上传的value
   * @param fileKey
   * @returns {*}
   */
  const setUrlKey = fileKey => formObj.setFieldsValue({ 'avatar': fileKey })

  /**
   * 重置的方法
   */
  const onReset = () => {
    form.resetFields()
  }

  return (
    <Modal
      destroyOnClose={true}
      title={`${type}用户`}
      visible={isModalVisible}
      onCancel={() => {modalIsShow(false)}}
      footer={null}
      onHandle={UserUrl}
      forceRender={true}
    >
      {
        // 只有是编辑的情况下 并且要显示的数据还没有返回 才显示骨架屏
        userInfoInitValues === undefined && editId !== undefined
          ?
          <Skeleton active/>
          :
          <ProForm
            submitter={{
              // 配置按钮文本
              searchConfig: {
                resetText: '重置',
                submitText: '提交',
              },
              // 配置按钮的属性
              resetButtonProps: {
                style: {
                  // 隐藏重置按钮
                  display: 'none',
                },
              }
            }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 15 }}
            labelAlign={'right'}
            form={formObj}
            initialValues={userInfoInitValues}
            name="control-ref"
            onFinish={values => handleSubmit(values)}>
            <Form.Item
              name="username"
              label="登录名"
              rules={[{ required: true, message: '请填写登录名' }]}>
              <Input placeholder={'请填写登录名'}/>
            </Form.Item>
            <Form.Item
              name="name"
              label="用户名"
              rules={
                [
                  {
                    required: true,
                    message: '请填写用户名'
                  }
                ]}
            >
              <Input placeholder={'请填写用户名'}/>
            </Form.Item>
            <Form.Item
              name="avatar"
              label="用户头像"
            >
              <div>
                <FileUpload
                  onHandle={EditUserUrl}
                  accept="image/*"
                  setUrlKey={setUrlKey}
                  listType={'picture-card'}
                >
                  {editId === undefined ?
                    <img src={UserUrl} width={'100%'} height={'100%'} alt=""/>
                    : <img src={UserUrl} width={'100%'} height={'100%'} alt=""/>}
                </FileUpload>
              </div>
            </Form.Item>
            <Form.Item name="id" hidden={true}>
              <Input/>
            </Form.Item>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                {
                  required: true,
                  message: '请填写邮箱',
                },
                {
                  type: 'email',
                  message: '邮箱格式不合法',
                }
              ]
              }
            >
              <Input placeholder={'请填写邮箱'}/>
            </Form.Item>
            <Form.Item
              name="phone"
              label="手机号"
              rules={[
                {
                  required: true,
                  message: '请填写手机号'
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式不合法'
                }
              ]
              }>
              <Input placeholder={'请填写手机号'}/>
            </Form.Item>
            {
              // 只有添加才有密码框
              editId === undefined ? <Form.Item
                name="password"
                label="密码"
                rules={[
                  {
                    required: true,
                    message: '请填写密码',
                  },
                  {
                    min: 6,
                    message: '密码最少6位',
                  },
                ]
                }>
                <Input.Password placeholder={'请填写密码'}/>
              </Form.Item> : ''
            }
            <Form.Item
              name="id_card"
              label="身份证"
            >
              <Input/>
            </Form.Item>
            <Form.Item
              name="section"
              label="部门"
            >
              <TreeSelect
                multiple={true}
                showSearch
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择部门"
                allowClear
                treeDefaultExpandAll
                treeData={treeData}
              >
              </TreeSelect>
            </Form.Item>
            {
              editId === undefined
                ?
                <Form.Item name="roles" label="角色">
                  <Checkbox.Group>
                    {allRoles.map((item) => {
                      return (<Checkbox key={item.id} value={item.id} style={{ lineHeight: '32px' }}>
                        {item.cn_name}
                      </Checkbox>)
                    })}
                  </Checkbox.Group>
                </Form.Item>
                : <Form.Item
                  name="roles"
                  label="角色"
                >
                  <Checkbox.Group>
                    {allRoles.map((item) => {
                      return (<Checkbox
                        key={item.id}
                        value={item.id}
                        checked={
                          userInfoInitValues.roles ?
                            (userInfoInitValues.roles.indexOf(item.id) !== -1)
                            : ''
                        }
                        style={{ lineHeight: '32px' }}>
                        {item.cn_name}
                      </Checkbox>)
                    })}
                  </Checkbox.Group>
                </Form.Item>
            }
          </ProForm>
      }
    </Modal>
  )
}

export default CreateOrEdit
